import { ElMessage, ElLoading } from 'element-plus'
// console.log(process.env.VUE_APP_API_URL);//不同的环境下面的baseurl
import axios, { AxiosResponse } from 'axios';
import store from '../store';
import { nextTick } from 'vue';
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
const service = axios.create({
    baseURL: 'http://localhost:3007/', //process.env.VUE_APP_API_URL,//'http://localhost:3007/',
    timeout: 10000
})
let loadObj: LoadingInstance;

// 请求拦截
service.interceptors.request.use(function (config) {
    // token
    if (store.getters.token) {
        config.headers["user-token"] = store.getters.token
    }

    // 旋转小图标的开始
    if (!loadObj) {
        loadObj = ElLoading.service({
            text: "加载中...",
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
            lock: true
        })
    }
    return config;
}, function (err) {
    return err;
})

// 响应拦截
service.interceptors.response.use(function (res: AxiosResponse) {
    nextTick(() => {
        loadObj.close()
    })
    if (res.data.msg == 'success') {
        return res;
    } else {
        ElMessage.error(res.data.msg);
        return res
    }

}, function (err) {
    return err
})

export default service;